#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/file.h>
#include "cache_table.h"

#define CACHE_TABLE_PATH "/usr/local/traker/cache-table"

/* this structure will be write out to hard disk directly,
and loaded in next time */
struct cache_disk_struct
{
	int nr_cache;
	struct cache_disk_part cache[MAX_CAHCE];
};

int file_exist(char *pathname)
{
	return access(pathname, F_OK) == 0 ? 1 : 0;
}

int load_cache(int *num, struct cache_disk_part cache[MAX_CAHCE])
{
	int fd;
	struct cache_disk_struct s = {0, };

	if (!file_exist(CACHE_TABLE_PATH))
	{
		if ((fd = open(CACHE_TABLE_PATH, O_WRONLY | O_CREAT)) < 0)
			return -1;
		if (write(fd, &s, sizeof(s)) != sizeof(s))
		{
			close(fd);
			return -1;
		}
		close(fd);
	}

	if ((fd = open(CACHE_TABLE_PATH, O_RDONLY)) < 0)
		return -1;
	flock(fd, LOCK_SH);
	if (read(fd, &s, sizeof(s)) != sizeof(s))
	{
		flock(fd, LOCK_UN);
		close(fd);
		return -1;
	}
	flock(fd, LOCK_UN);
	close(fd);

	*num = s.nr_cache;
	memcpy(cache, s.cache, sizeof(struct cache_disk_part) * s.nr_cache);
	return 1;

}
int save_cache(int num, struct cache_disk_part cache[MAX_CAHCE])
{
	int fd;
	struct cache_disk_struct s = {0, };

	s.nr_cache = num;
	memcpy(s.cache, cache, sizeof(struct cache_disk_part) * num);

	if ((fd = open(CACHE_TABLE_PATH, O_WRONLY)) < 0)
		return -1;
	flock(fd, LOCK_EX);
	if (write(fd, &s, sizeof(s)) != sizeof(s))
	{
		flock(fd, LOCK_UN);
		close(fd);
		return -1;
	}
	flock(fd, LOCK_UN);
	close(fd);
	return 1;
}
int load_cache_table(struct cache_table *ct)
{
	if (load_cache(&ct->nr_cache, ct->cache_d) < 0)
		return -1;
}





